package cn.nexd.app.collector.presenter.fileManager;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.nexd.app.collector.Thread.RecordThread;
import cn.nexd.app.collector.application.NexdApplication;
import cn.nexd.app.collector.model.LocationRecord;
import cn.nexd.app.collector.util.ProgressUtil;
import cn.nexd.app.collector.util.UMengUtil;
import cn.nexd.utils.framework.error.NexdCrashException;
import cn.nexd.utils.framework.tools.FileUtil;
import cn.nexd.utils.framework.tools.Logger;
import cn.nexd.utils.framework.tools.StringUtil;

/**
 * 导出定位测试时的定位数据
 * <p>
 * Created by wangxu on 16/11/29.
 */

public class FileManagerPresenter implements FileManagerContract.FileManagerPresenter {


    private static final String TAG = "FileManagerPresenter";

    private Context context;

    private FileManagerContract.FileManagerActivityView iView;


    private static final int READ_STEP = 3000;

    public FileManagerPresenter(Context context, FileManagerContract.FileManagerActivityView iView) {
        this.context = context;
        this.iView = iView;
    }

    @Override
    public List<String> getMalls() {

        List<String> mallLists = new ArrayList<>();

        Cursor cursor = NexdApplication.getInstance().getSqlHelper().getDb().rawQuery("select * from mall", null);

        while (cursor.moveToNext()) {
            mallLists.add(cursor.getString(cursor.getColumnIndex("mallId")));
        }
        closeCursor(cursor);
        return mallLists;
    }

    @Override
    public void exportAllMallsSignal(List<String> malls) {


        if (RecordThread.getRecordThread().getQueueSize() != 0) {
            Logger.debug(TAG, "exportAllMallsSignal: queue size = " + RecordThread.getRecordThread().getQueueSize());
            iView.showToast("数据还未存储完成，请稍后重试！");
            return;
        }

        Log.d(TAG, "exportAllMallsSignal: mall size :" + malls.size());
        ProgressUtil.show(context, "提示", "正在导出....", false);
        new Thread(new Runnable() {
            @Override
            public void run() {

                List<String> malls = getMalls();

                if (malls.size() == 0) {
                    notifyForward("本地数据为空!");
                    return;
                }

                for (String mallId : malls) {
                    // 获取总数据量
                    int count = getCount(mallId);
                    // 根据总数据量确定循环次数，以及每次分页查询的起始位置
                    int startIndex = 0;
                    int endIndex = READ_STEP;

                    int index = count / READ_STEP;

                    if (index != 0) {
                        for (int i = 0; i < index; i++) {

                            if (i < index) {
                                startIndex = i * READ_STEP;
                            }
                            export(mallId, startIndex, endIndex);
                            if (i == index - 1) {
                                startIndex = (i + 1) * READ_STEP;
                                endIndex = count - startIndex;
                                export(mallId, startIndex, endIndex);
                            }

                        }
                    } else if (count != 0) {

                        startIndex = 0;

                        endIndex = count;

                        export(mallId, startIndex, endIndex);
                    }

                    dropTable(mallId);

                }

                deleteMall();

                zipExportFiles(NexdApplication.BASE_EXPORT_FILE_PATH + "mall/", NexdApplication.BASE_EXPORT_FILE_PATH + "export_" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date()));

                notifyForward("导出完成！");
            }

        }).start();
    }

    private void deleteMall() {
        NexdApplication.getInstance().getSqlHelper().getDb().execSQL("delete from mall");
    }


    private void notifyForward(final String msg) {
        ((Activity) context).runOnUiThread(new Runnable() {

            @Override
            public void run() {
                iView.showToast(msg);
            }
        });

        ProgressUtil.dismiss();
    }

    private void zipExportFiles(String srcFilePath, String targetFilePath) {
        try {
            FileUtil.compressFile(new File(srcFilePath), targetFilePath);
            FileUtil.deleteFile(srcFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            UMengUtil.getInstance().reportError(context, e);
            NexdCrashException.getInstance().reportException(e);
        }
    }

    private void dropTable(String mallId) {
        if (NexdApplication.getInstance().getSqlHelper().tableIsExist("mall_" + mallId)) {
            NexdApplication.getInstance().getSqlHelper().getDb().execSQL("drop table mall_" + mallId);
        }
    }

    private List<LocationRecord> locationRecords = new ArrayList<>();

    private void export(String mallId, int startIndex, int endIndex) {
        if (!NexdApplication.getInstance().getSqlHelper().tableIsExist("mall_" + mallId)) {
            return;
        }
        Cursor cursor = NexdApplication.getInstance().getSqlHelper().getDb().rawQuery("select * from mall_" + mallId + " limit " + endIndex + " offset " + startIndex, null);
        while (cursor.moveToNext()) {
            LocationRecord locationRecord = new LocationRecord();
            locationRecord.setMallId(cursor.getLong(cursor.getColumnIndex("mallId")));
            locationRecord.setFloorId(cursor.getLong(cursor.getColumnIndex("floorId")));
            locationRecord.setPosition(cursor.getString(cursor.getColumnIndex("position")));
            locationRecord.setSignal(cursor.getString(cursor.getColumnIndex("signal")));
            locationRecord.setDate(cursor.getLong(cursor.getColumnIndex("date")));
            locationRecords.add(locationRecord);
        }
        closeCursor(cursor);
        writeToFile(mallId, locationRecords);
    }

    private StringBuilder builder = new StringBuilder();

    private void writeToFile(String mallId, List<LocationRecord> records) {
        for (LocationRecord record : records) {
            builder.append(record.getMallId())
                    .append(" ")
                    .append(record.getFloorId())
                    .append(" ")
                    .append(record.getPosition())
                    .append(StringUtil.unCompress(record.getSignal()))
                    .append(" ")
                    .append(record.getDate())
                    .append("\n");
        }

        try {
            FileUtil.writeFile(NexdApplication.BASE_EXPORT_FILE_PATH + "mall/" + mallId + ".txt", builder.toString());
            builder.setLength(0);
            locationRecords.clear();
        } catch (IOException e) {
            e.printStackTrace();
            UMengUtil.getInstance().reportError(context, e);
            NexdCrashException.getInstance().reportException(e);
        }
    }

    private int getCount(String mallId) {
        if (!NexdApplication.getInstance().getSqlHelper().tableIsExist("mall_" + mallId)) {
            return 0;
        }

        Cursor cursor = NexdApplication.getInstance().getSqlHelper().getDb().rawQuery("select count(1) from mall_" + mallId, null);
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        closeCursor(cursor);
        return count;
    }

    private void closeCursor(Cursor cursor) {
        if (cursor != null) {
            cursor.close();
        }
    }

    @Override
    public void init() {

    }
}
